<template>
	<view class="book-recommend-container">
		<view class="recommend-header">
			<text class="recommend-title">猜你喜欢</text>
		</view>
		<view class="recommend-grid">
			<navigator v-for="(recommendBook, idx) in recommendBookData" :key="idx" class="recommend-item"
				:url="`/pages/book/index?bookId=${recommendBook.id}`">
				<image class="recommend-image" :src="`${baseURL}${recommendBook.image}`" mode="aspectFill" />
				<view class="book-name">
					{{ recommendBook.name }}
				</view>
				<view class="book-description">
					{{ recommendBook.description }}
				</view>
			</navigator>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { pageRecommendsAPI } from '@/services/bookstore'
	import { commonPageQueryData } from '@/services/global'
	import { BookItem } from '../types/book'
	import { PageParams } from '../types/global'
	import { baseURL } from '@/utils/config'
	import { onMounted, ref } from 'vue'
	// 推荐列表
	const recommendBookData = ref<BookItem[]>([])
	/**
	 * 页面加载完成后加载数据
	 */
	onMounted(() => {
		// 请求参数
		queryParams.value.sourceType = query.sourceType
		// 加载推荐列表数据
		pageQueryRecommendListData()
	})
	// 是否加载完成
	const finish = ref(false)
	// 是否正在加载
	const isLoading = ref(true)
	// 分页参数
	const pageParams : Required<PageParams> = {
		current: 1,
		size: 8
	}
	// 查询参数
	const queryParams = ref({
		sourceType: ''
	})
	/**
	 * 分页加载数据
	 * @returns  void
	 */
	const pageQueryRecommendListData = async () => {

		await commonPageQueryData(
			pageRecommendsAPI,
			recommendBookData,
			finish,
			isLoading,
			pageParams,
			queryParams
		)

		recommendBookData.value.forEach((item, index) => {
			item.description = item.description!.slice(0, 20) + '...'
		})
	}

	/**
	 * 触底加载更多数据
	 */
	const handleScrollToLower = () => {
		// console.log('handleScrollToLower' + query.sourceType)
		pageQueryRecommendListData()
	}
	/**
	 * 将handleScrollToLower暴露给父组件
	 */
	defineExpose({
		handleScrollToLower
	})

	/**
	 * 接收父组件传递的参数，来源字段sourceType
	 */
	const query = defineProps<{ sourceType : string }>()
</script>

<style lang="scss" scoped>
	/* stylelint-disable */
	.book-recommend-container {
		height: 100vh;
		margin: 0.5rem;
	}

	.recommend-header {
		padding: 1rem;
	}

	.recommend-title {
		font-weight: bold;
	}

	.recommend-grid {
		display: grid;
		grid-template-columns: repeat(2, minmax(0, 1fr));
		gap: 0.5rem;
	}

	.recommend-item {
		height: 320px;
		border-radius: 0.5rem;
		background-color: white;
		box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
	}

	.recommend-image {
		width: 100%;
		height: 200px;
		border-top-left-radius: 0.5rem;
		border-top-right-radius: 0.5rem;
	}

	.book-name {
		white-space: normal;
		margin-top: 0.5rem;
		padding-left: 0.25rem;
	}

	.book-description {
		font-size: 0.875rem;
		color: #6b7280;
		margin-top: 0.5rem;
		padding-left: 0.5rem;
	}
</style>